package server.Handler;

import attribute.Attributes;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import protocol.request.MessageRequest;
import protocol.response.MessageResponse;
import session.Session;
import util.SessionUtil;

import java.util.Date;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequest messageRequest) throws Exception {
        Session session = SessionUtil.getSession(ctx.channel());
        System.out.println(new Date() + ":服务端接收到用户【" + session.getUserName() + "】，发送给【" + session.getUserId() + "】的消息【" + messageRequest.getMessage() + " 】");

        MessageResponse messageResponse = new MessageResponse();
        messageResponse.setMessage(messageRequest.getMessage());
        messageResponse.setFromUserId(session.getUserId());
        messageResponse.setFromUserName(session.getUserName());

        Channel toUserChannel = SessionUtil.getChannel(messageRequest.getToUserId());

        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponse);
        }else {
            System.out.println("【" + messageRequest.getToUserId() + "】不在线，发送失败!");
        }

        ctx.channel().writeAndFlush(messageResponse);
    }
}
